import { app, BrowserWindow } from 'electron'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import {handleRequestApi} from "./webSession.ts";
import {CusIpcMain} from "./cusIpcMain.ts";

createRequire(import.meta.url);
const __dirname = path.dirname(fileURLToPath(import.meta.url))
process.env.APP_ROOT = path.join(__dirname, '..')

export const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, 'public') : RENDERER_DIST

let win: BrowserWindow | null
const createWindow=()=> {
  const mainWin = new BrowserWindow({
    icon: path.join(process.env.VITE_PUBLIC, 'electron-vite.svg'),
    autoHideMenuBar:true,
    frame:false,
    webPreferences: {
      webviewTag:true,
      contextIsolation:true,
      nodeIntegration:true,
      preload: path.join(__dirname, 'preload.mjs'),
    },
  })
  if (VITE_DEV_SERVER_URL) {
    mainWin.loadURL(VITE_DEV_SERVER_URL)
  } else {
    mainWin.loadFile(path.join(RENDERER_DIST, 'index.html'))
  }
  return mainWin
}
const InitWindow = () => {
  win=createWindow()
  new CusIpcMain(win);
}
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
    win = null
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    InitWindow()
  }
})
app.whenReady().then(()=>{
  InitWindow()
})
